package com.jhy.system.consumer;

import cn.hutool.json.JSONUtil;
import com.jhy.core.utils.Check;
import com.jhy.core.utils.redis.RedisUtils;
import com.jhy.system.domain.vo.SysUserFriendVo;
import com.jhy.system.service.ISysUserFriendService;
import com.jhy.ws.constants.WebSocketConstant;
import com.jhy.ws.domain.bo.WsMsgRecordBo;
import com.jhy.ws.factory.WebsocketTypeFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@RequiredArgsConstructor
public class WsOnlineStatusRedisConsumer {

    private final ISysUserFriendService friendService;

    @PostConstruct
    public void start() {
        RedisUtils.subscribe(WebSocketConstant.ONLINE_STATUS_QUEUE, WsMsgRecordBo.class,msg -> {
            WsMsgRecordBo bean = JSONUtil.parseObj(msg).toBean(WsMsgRecordBo.class);
            log.info("收到在线状态消息：{}", bean);
            if (Check.isNoEmpty(bean.getFromUser())){
                List<SysUserFriendVo> friendVos = friendService.findFriendByUserName(bean.getFromUser());
                if (Check.isNoEmpty(friendVos)){
                    for (SysUserFriendVo item : friendVos) {
                        bean.setTarget(item.getUserId().equals(bean.getFromUserId()) ? item.getFriendUserName() : item.getUserName());
                        bean.setTargetId(item.getUserId().equals(bean.getFromUserId()) ? item.getFriendUserId().toString() : item.getUserId().toString());
                        try {
                            WebsocketTypeFactory.instance(bean).sendMsg();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
//        scheduler.scheduleAtFixedRate(this::pullMessage, 0, 1200, TimeUnit.MILLISECONDS);
    }

    @PreDestroy
    public void stop() {
        RedisUtils.unsubscribe(WebSocketConstant.ONLINE_STATUS_QUEUE);
    }

}
